import { Application, HttpClientResponse } from "egg";
import CodoBase from "../../CodoBase";
import { dahua } from "./type";
import CodoError from "../../CodoError";
import { HttpClientResponse as HttpClientResponseOld } from "urllib";

const symbolToken = Symbol("accessToken");

export class DaHuaICCBaseService extends CodoBase {
	constructor(app: Application, public readonly config: dahua.icc.ICCConfig) {
		super(app);
	}

	protected get accessToken() {
		if (!this[symbolToken]) throw new CodoError(`Access Token is not set.`);
		return this[symbolToken] as string;
	}

	setAccessToken(accessToken: string) {
		this[symbolToken] = accessToken;
	}

	handleResponseException(
		res: HttpClientResponse<dahua.icc.IResponse> | HttpClientResponseOld<dahua.icc.IResponse>,
		errmsg: string = "-"
	) {
		if (res.status !== 200) {
			throw new CodoError(`dahua.icc 请求出错 %s\r\n %s`, (res as any).url, errmsg);
		}
		if (res.data.code !== "0") {
			throw new CodoError(
				`dahua.icc 业务异常 %s\r\n %s\r\n %s %s`,
				(res as any).url || "",
				errmsg,
				res.data.code,
				res.data.errMsg
			);
		}
	}
}
